/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.vod.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 
 * @author dRazanakoto
 */
public class ReceiverMulticast extends Receiver {

	private MulticastSocket socket;
	private final int BUFFER_SIZE = 1024;

	/**
	 * 
	 * @param ip
	 * @param port
	 */
	public ReceiverMulticast(InetAddress ip, int port) throws Exception {
		super(ip, port);
		socket = new MulticastSocket(port);
		socket.joinGroup(ip);
		if (socket.isConnected())
			System.out.println("Multicast Connecté");
		if (socket.isBound())
			System.out.println("socket bound");
		
		startWatching();
	}

	@Override
	public String receive() throws Exception {
		byte[] bytes = new byte[BUFFER_SIZE];
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		socket.receive(packet);
		
		addReceivedBytes(packet.getLength(), System.currentTimeMillis());
		return new String(packet.getData()).trim();
	}

	@Override
	public DatagramPacket receivePacket(int heartbeatSleep) throws IOException {
		byte[] bytes = new byte[BUFFER_SIZE];
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		socket.setSoTimeout(heartbeatSleep);
		try {
			socket.receive(packet);
		} catch (IOException e) {
			socket.setSoTimeout(0);
			throw e;
		}
		socket.setSoTimeout(0);
		
		addReceivedBytes(packet.getLength(), System.currentTimeMillis());
		return packet;
		// return new String(packet.getData(),"UTF-8");
	}

	@Override
	public String receive(int timeout) {
		byte[] bytes = new byte[BUFFER_SIZE];
		String msg = "";
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		try {
			socket.setSoTimeout(timeout);
			socket.receive(packet);
			msg = new String(packet.getData()).trim();
			socket.setSoTimeout(0);
		} catch (Exception e) {
			return "";
		}
		
		addReceivedBytes(packet.getLength(), System.currentTimeMillis());
		return msg;
	}

	@Override
	public DatagramPacket receivePacket() throws Exception {
		byte[] bytes = new byte[BUFFER_SIZE];
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
		socket.receive(packet);
		
		addReceivedBytes(packet.getLength(), System.currentTimeMillis());
		return packet;
	}
}
